<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users_model extends CI_Model {

	public function __construct()
	{
            parent::__construct();
            $this->load->helper('url');
	}
  
        /* 
         * All the fuctions to deal with Users
         */
        
        public function getuserlist($area = 'all') {
            /*
             * Retuns a list of users by area or the default is (all) for all system users
             * db.users.insert({'Name': 'Anton Foster', 'username': 'anton@kelsamfos.com', 'passwd': 'kelsam',
             * 'role': 'admin', 'mobile': '0832271065', 'level': 1, 'created': new Date(), 'active': true, 
             * 'verified': true, 'areas': [{'area' : '5124d0b806c5e53197c1564c', 'areaname' : 'Farmall A/H Ext 1'}], 
             * 'grp' : [{'grpid': '512a4f9912f0feb59755da95', 'grpname': 'Farmall Chartwell' }] } )
             */
            
            if ($area == 'all') {
                // Return all
               $result = $this->mongo_db->get('users');
               $data = [];
               
                foreach ($result as $data1) {
                    $data[] = array(
                    'id' => $data1["_id"]->__toString(),
                    'Name' => $data1['Name'],
                    'username' => $data1['username'],
                    'role' => $data1['role'],
                    'mobile' => $data1['mobile'],
                    'level' => $data1['level'],
                    'created' => $data1['created'],
                    'active' => $data1['active'],
                    'grp' => $data1['grp'],
                    'areas' => $data1['areas'] ); 
                }
               
            } else {
                /*
                 * Here we return only the users registered in an area
                 */
                $result = $this->mongo_db
                          ->where_in('areas', array(
                            $area ))
                          ->select(array('Name', 'username', 'mobile'))
                          ->get('users');
           }
            return $data;
        }
        
        public function updatepass($uid, $upass) {
            /*
             * Updates a users password
             */
            $criteria = array('_id' => new MongoId($uid)) ;
            $this->mongo_db->set($upass)->where($criteria)->update('users');
        }


        public function getuserbyid( $uid ) {
            /*
             * Returns a single user
             */
            $theuserId = new MongoId($uid); 
            $result = $this->mongo_db->where(array("_id" => $theuserId))->get('users');
            // var_dump($result);
            return $result;
        }
        
        public function getareabyid( $aid ) {
            /*
             * Returns a single area
             */
            $theId = new MongoId($aid); 
            $result = $this->mongo_db->where(array("_id" => $theId))->get('area');
            // var_dump($result);
            return $result;
        }
        
        public function saveuser ($uid, $data ) {
           /*
            * Updates a single users details 
            */ 
           $criteria = array('_id' => new MongoId($uid)) ;
           $this->mongo_db->set($data)->where($criteria)->update('users'); 
            
        }

        
        /*
         * All the fuctions to deal with Registration
         * including canceling a registration
         * and moderation of registrations
         */
        
        public function checkemailun($email) { // tuned for Ajax call in registration
           /* 
            * checks for duplicate email address in either the users collection or in the registration collection 
            */
            $r1 = count($this->mongo_db->where( array("username" => $email) )->get('users'));
            $r2 = count($this->mongo_db->where( array("username" => $email) )->get('registration'));
            return $r1 + $r2;
        }
        
        public function SaveReg ( $data ) {
           /*
            * This function collates and saves a new user registration request
            */ 
           
           // build the data
           $data1['Name'] = $data['Name'];
           $data1['username'] = $data['username'];
           $data1['regtypetype'] = $data['regtypetype'];
           $data1['accepttandc'] = TRUE;
           $data1['acceptprivacy'] = TRUE;
           $data1['mobile'] = $data['mobile'];
           $data1['address'] = $data['address'];
           $data1['motivation'] = $data['motivation'];
           $data1['action'] = 'pending';
           $data1['roadnum'] = '';
           $data1['role'] = 'public';
           $data1['street'] = '';
           $data1['status'] = 'open';
           $data1['emailvrified'] = FALSE;
           $data1['addressverified'] = FALSE;
           $data1['IPaddress'] = $data['IPaddress'];
           $data1['datesumbit'] = new MongoDate() ; // date('j-m-Y h:i:s');
           $data1['checkedby'] = array('uid' => '', 'uname' => '', 'ipaddress' => '', 'regdate' => '');
           $data1['Comments'] = [];
           /*
            *  Get the area name
            */
           $ar = $this->getareabyid( $data['areas'] );
           if (count($ar) > 0) {
                $data1['areas'] = array('aid' => $data['areas'], 'areaname' => $ar[0]['Area']) ;
           }
           $res = $this->mongo_db->insert('registration', $data1);
           if ($res == FALSE) { $id = FALSE; 
            } else {
                $id = $res->__toString();
                   }
           return $id;
        }
        
        public function insertnewuser ($data) {
           $res = $this->mongo_db->insert('users', $data); 
           return $res;
        }


        public function getregvalidbyid( $id ) {
            /*
             *  checks if the registration is on file and that the email address has not been validated
             */
            $criteria = array('_id' => new MongoId($id), 'emailvrified' => FALSE ) ;
            $reg = $this->mongo_db->where($criteria)->get('registration'); 
            if (count($reg) > 0) {
                return $reg;
            } else {
                return FALSE;
            }    
        }
        
        public function getregbyusername( $email ) {
            /*
             *  checks if the registration is on file and that the email address has not been validated
             */
            $criteria = array('username' => $email ) ;
            $reg = $this->mongo_db->where($criteria)->get('registration'); 
            if (count($reg) > 0) {
                return $reg;
            } else {
                return FALSE;
            }    
         }
         
       public function MoveRegdata( $id ) {
            /*
             *  Gets the registration data and then copies it to collection called registrationarchive
             *  then it deletes the record in registration
             */
            $criteria = array ('_id' => new MongoId($id) ) ;
            $reg = $this->mongo_db->where($criteria)->get('registration');  
            $indata = array('oid' =>  $id, 'Name' => $reg[0]['Name'], 'username' => $reg[0]['username'], 'mobile' => $reg[0]['mobile'],'IPaddress' => $reg[0]['IPaddress'] ,'areas' => $reg[0]['areas'], 
               'regtypetype' => $reg[0]['regtypetype'], 'action' => $reg[0]['action'], 'status' => $reg[0]['status'], 'emailvrified' => $reg[0]['emailvrified'], 
                'addressverified' => $reg[0]['addressverified'], 'canreason' => $reg[0]['canreason'], 'audit' => $reg[0]['Comments']);
            $this->mongo_db->insert('registrationarchive', $indata);
            $done = $this->mongo_db->delete('registration', $criteria);
            
            return $done;
         }
        
        
        public function cancelreg( $id, $reason ) {
            /*
             *  Cancel the registration with a reason
             */
            $criteria = array('_id' => new MongoId($id)) ;
            $this->mongo_db->where($criteria)->set(array('status' => $reason['status'], 'action' => 'cancel', 'status' => 'cancel' ))->update('registration'); 
            $this->mongo_db->where($criteria)->push(array('canreason' => array('reason' => $reason['reason'], 'datecancel' => new MongoDate(), 'IPaddress' => $reason['IPaddress'])))->update('registration');
            $c = array('rid' => $id, 'Name' => 'System', 'comment' => 'Registration cancelled by User');
            $this->insertRegComment($c);
            $done = $this->MoveRegdata($id);
            return $done;
            /* Update the comments as well */
            
        }
        
        public function getregdatabyid( $id ) {
            /*
             *  checks if the registration is on file and then returns the data or FALSE
             */
            $criteria = array('_id' => new MongoId($id) ) ;
            $reg = $this->mongo_db->where($criteria)->get('registration'); 
            if (count($reg) > 0) {
                return $reg;
            } else {
                return FALSE;
            }    
            
        }
        
        public function uemailreg($id) {
           /*
            *  If the Registration email verification is still pending the email address verification is set to TRUE 
            */
           $criteria = array('_id' => new MongoId($id)) ;
           $this->mongo_db->set(array('emailvrified' => TRUE, 'action' => 'validate', 'status' => 'evaled'))->where($criteria)->update('registration');  
           $c = array('rid' => $id, 'Name' => 'System', 'comment' => 'Email Address validated via link');
           $this->insertRegComment($c);
       }
       
       public function insertRegComment($comment) {
        /*
         * Inserts a comment into the registration 
         */   
        $criteria = array('_id' => new MongoId($comment['rid'])) ;
        $ch = $this->mongo_db
                ->push(array('Comments' => array('PostedBy' => $comment['Name'], 'PostedOn' => new MongoDate(), 'PostName' => $comment['comment'])))
                ->where($criteria)
                ->update('registration');   
        if (count($ch) > 0) {
           return TRUE ;
        } else {
           return FALSE;
        }
       }
       
       
       
       public function GetRegComments($rid) {
           /*
            * Gets all the comments for a registration
            */
        $criteria = array('_id' => new MongoId($rid)) ;   
        $comm = $this->mongo_db->select('Comments')->where($criteria)->get('registration'); 
        // var_dump($comm);
        if (count($comm[0]['Comments']) > 0) {
        $data = [];
               foreach ($comm[0]['Comments'] as $rdata) {
                  $data[] = array(
                    'PostedBy' => $rdata["PostedBy"],
                    'PostedOn' => $rdata['PostedOn'],
                    'PostName' => $rdata['PostName']);
                }
               // var_dump($data);
               return $data; 
               } else { 
                   return FALSE; 
               } 
       }


       public function getReglist($param) {
           /*
            * Returns a list of registrations based on either Super User
            * ie no restrictions or by area
            * and by different types of action status
            * called from users (listRegistration())
            */
           $selected = array('Name', 'action', 'status', 'emailvrified', 'address', 'username', 'mobile' );
           if ($param['area'] == '') {
               /*
                * Super User Listings
                */
               if ($param['action'] == '') {
                   /*
                    * Get all listings accross all areas
                    */
                   $reg = $this->mongo_db->select($selected)
                               ->get('registration');  
               } else {
                   /*
                    * Filter lists
                    */   
                   $reg = $this->mongo_db->select($selected)
                               ->where(array('action' => $param['action']))
                               ->get('registration'); 
               }
           } else {
               /*
                * Area Listings
                */
               if ($param['action'] == '') {
                   /*
                    * Get all listings accross all areas
                    * 5124d0b806c5e53197c1564c
                    */
                //   $win = array('areas' => array('aid' => $param['area']));
                 ///  ->where_in('areas', array($area ))
                   $win = array($param['area']);
                   $reg = $this->mongo_db->where_in( 'areas.aid', $win )->get('registration');
                // $reg = $this->mongo_db->where_in('areas.aid', array( '5124d0b806c5e53197c1564c' ))->get('registration');
                   
               } else {
                   /*
                    * Filter lists
                    */  
                   $win = array($param['area']);
                   $reg = $this->mongo_db->where_in( 'areas.aid', $win )
                           ->where(array('action' => $param['action']))
                           ->get('registration');
                   
               }
               
           }
           if (count($reg) > 0) {
               /*
                * Convert to useable array
                */
               $data = [];
               foreach ($reg as $rdata) {
                   if($rdata['emailvrified']) {$em = 'Verified';} else {$em = 'Unverified';}
                    $data[] = array(
                    'rid' => $rdata["_id"]->__toString(),
                    'Name' => $rdata['Name'],
                    'username' => $rdata['username'],
                    'action' => $rdata['action'],
                    'status' => $rdata['status'],
                    'emailvrified' => $em,
                    'address' => $rdata['address'] , 
                    'mobile' => $rdata['mobile'] );
                }
               // var_dump($data);
               return $data; 
               } else { 
                   return FALSE; 
               } 
       }

       public function updateregistration($rid, $data) {
       /*
        * Update the registration details during the moderation process
        */    
       $criteria = array('_id' => new MongoId($rid)) ;
       $reg = $this->mongo_db->set( $data )
                           ->where($criteria)
                           ->update('registration');
       }





       /*
        * All functions relating to Property Management
        * 
        * 
        */
       
       
        public function getproplist ($param = 'all') {
             /*
              *  Retuns a list of properties by area or the default is (all) for all system users
              */
            if ($param == 'all') {
                // Return all
                $result = $this->mongo_db->get('property');
            } else {
                $cr = array( $param );
             // var_dump($cr);
                /// STILL NOT WORKING
                $result = $this->mongo_db
                          ->where_in_all($cr)
                          ->select(array('Name', 'roadnum', 'street', 'intersect', 'gps', 'area', 'Owner'))
                          ->get('property');
               // var_dump($result);
            }
            $data = [];
            foreach ($result as $data1) {
               $data[] = array(
                'id' => $data1["_id"]->__toString(),
                'Name' => $data1['Name'],
                'roadnum' => $data1['roadnum'],
                'street' => $data1['street'],
                'intersect' => $data1['intersect'],
                'gps' => $data1['gps'],
                'area' => $data1['area'],
                'Owner' => $data1['Owner'] ); 
            }
          return $data;
        }
        
        public function getpropbyid($pid) {
            /*
             * Returns a propety details for the mongo _id passed
             */
            $criteria = array('_id' => new MongoId($pid)) ;
            $result = $this->mongo_db
                          ->where($criteria)
                          ->limit(1)
                          ->get('property');
            return $result;
        }

       public function updateprop ($pid, $data ) {
           /*
            * Updates a single property
            */
           $criteria = array('_id' => new MongoId($pid)) ;
           $result = $this->mongo_db->set($data)->where($criteria)->update('property'); 
           return $result; 
        }
        
        public function GetPropertyById ( $pid ) {
           /*
            * retrieves a single property in the _id (pid)
            */
           $criteria = array('_id' => new MongoId($pid)) ;
           $result = $this->mongo_db->where($criteria)->get('property'); 
           if (count($result) > 0) {
               return $result; } 
           else {
             return FALSE;     
           }
            
        }
        
        public function insertprop ($data ) {
           /*
            * Inserts a new property
            * First check that it does not exsist
            */
            $where = array('roadnum' => $data['roadnum'], 'street' =>  $data['street']);
            $wherein = array('area.aid', array($data['area']['aid']));
            $ch = $this->mongo_db
                          ->where($where)
                          ->where_in('area.aid', array($data['area']['aid']))
                          ->limit(1)
                          ->get('property');
           // echo '<script type="text/javascript"> alert("SQL : '. var_dump($wherein) . '"); </script>;';
            if (count($ch) == 0) {
              $result = $this->mongo_db->insert('property', $data); 
              return $result;
                } else {
                return FALSE;
                }
        }
        
        public function findproperty($pnum, $street, $aid) {
            /*
             * Function to determin if a property is registered in an area by house
             * number and street. If it exsists it will return the full data of the property
             * else FALSE
             */
            $where = array('roadnum' => $pnum, 'street' => $street) ;
            $wherein = array('area.aid', array($aid));
            // where_in($wherein)->
            $result = $this->mongo_db->where($where)->where_in( 'area.aid', array($aid) )->get('property');
            // echo '<script type="text/javascript"> alert("SQL : '. var_dump($result) . '"); </script>;';
            if (count($result) > 0) {
                /* Record returned */
                return $result;
            } else {
                return FALSE;
            }
        }




        /*
         * Utilities like area's Groups etc
         * 
         */
                
        public function liststreetbyarea($aid = '') {
            /*
             * Lists all the streets for an area
             */
           //var_dump($aid); 
           if ($aid != '') {
           $result = $this->mongo_db
                   ->where(array('Area' => $aid))
                   ->get('street'); 
           if (count($result) > 0) {
           $data = [];
           foreach ($result as $data1) {
               $data[] = array(
                'id' => $data1["_id"]->__toString(),
                'Street' => $data1['Street'],
                'AreaName' => $data1['AreaName'] ); 
            }
           } else {$data = FALSE; }
           }
           
           // var_dump($data); 
            return $data; 
        }
       
        public function getareas() {
            /*
             * Returns a list of all areas
             */
            $result = $this->mongo_db->get('area');
            $data = [];
            foreach ($result as $area) {
               $data[] = array(
                'id' => $area["_id"]->__toString(),
                'Area' => $area['Area'],
                'Display' => $area['Display'],
                'Description' => $area['Description'],
                'admin' => $area['admin'],
                'gisbounds' => $area['gisbounds'],
                'cpf' => $area['cpf'],
                'council' => $area['council'],
                'map' => $area['map'] ); 
            }
              // var_dump($result);
            return $data;
        }
        
        
        public function getroles($level = 2) {
            /*
             * Retrns a list of all roles
             */
             $result = $this->mongo_db->where_gte('level', $level)->get('roles');
            // var_dump($result);
            return $result;
        }
        
        public function getgroups() {
            /*
             * Returns a list of all groups
             */
             $result = $this->mongo_db->get('areagroups');
            $data = [];
            foreach ($result as $group) {
               $data[] = array(
                'id' => $group["_id"]->__toString(),
                'GroupName' => $group['GroupName'],
                'GroupDescr' => $group['GroupDescr'],
                'AreaList' => $group['AreaList']);
                
            }
              // var_dump($result);
            return $data;
        } 
        
        public function logerrors($info, $error) {
          $ins = array('info' => $info,  'username' => $_SESSION['email'], 'Name' => $_SESSION['Name'], 'ipaddress' => $_SESSION['IP'], 'ErrorDate' => new MongoDate(), 'error' => $error);  
          $this->mongo_db->insert('errorlog', $ins);  
        }
}
?>
